package com.zhiqianbao.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.creditx.xbehavior.sdk.ActionName;
import com.creditx.xbehavior.sdk.CreditXAgent;
import com.google.gson.Gson;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.AppInfo;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.Third;
import com.zhiqianbao.listener.MyLocationListener;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.CountDownButtonHelper;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.SystemUtils;
import com.zhiqianbao.utils.TimeStatisticsUtil;
import com.zhiqianbao.utils.WifiInfoUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;

/**
 * Created by liang on 2016/1/7.
 */
public class ApplyVerifyActivity extends BaseActivity {
    public static final int RESULT_ERROR = 0;

    WebView mWebView;
    /**
     * 勾选框
     */
    ImageView imageViewContract;
    /**
     * 查看协议
     */
    Button buttonContract;
    /**
     * 确认按钮
     */
    Button buttonApplyConfirm;
    private Button button_apply_confirm;
    /**
     * 是否勾选
     */
    boolean isChecked = false;
    private AlertDialog dialog;
    private PackageManager pm;
    private Map<String, String> params;
    private List<AppInfo> appInfos = new ArrayList<AppInfo>();
    private Drawable loadIcon;
    private String voucherPic;
    private String imei="";
    private String imsi="";
    Integer capital;
    Integer termLine;
    String contractNum;
    String couponId;

    String phoneJosn;
    boolean isUpload;
    private SharedPreferanceUtils sharedPreferanceUtils;
    private WifiManager wifiManager;
    private EditText et_getcode;
    private Button bt_code;
    private CountDownButtonHelper helper;
    private boolean isUploadInstallApp = false;//上传安装应用判断，进入页面后只上传一次
    private String startTimes="";

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            closeWaitDialog();
            switch (msg.what) {
                case RESULT_OK:
                    String result = (String) msg.obj;
                    Result data = Result.fromJson(result, Object.class);
                    showShortToast1(data.getMsg());
                    button_apply_confirm.setEnabled(true);
                    //保存成功，跳转到进度页面
                    if (Constants.DEFAULT_SUCCESS_CODE.equals(data.getCode())) {
                        CreditXAgent.onSubmit(ActionName.Submit.LOAN_SUBMISSION,
                                CreditXAgent.ActionStatus.SUCCESS,"提交成功");
                        uploadContacts();
                        Intent intent = new Intent(ApplyVerifyActivity.this, ApplyTabHostActivity.class);
                        intent.putExtra("userloginflag", 1);
                        setResult(RESULT_OK, intent);
                        ApplyVerifyActivity.this.finish();
                    }
                    else{
                        CreditXAgent.onSubmit(ActionName.Submit.LOAN_SUBMISSION,
                                CreditXAgent.ActionStatus.FAILED,"提交失败");
                    }
                    if (!isUploadInstallApp) {
                        isUploadInstallApp = true;
                        getInstallApp();
                    }
                    break;
                case RESULT_ERROR:
                    CreditXAgent.onSubmit(ActionName.Submit.LOAN_SUBMISSION,
                            CreditXAgent.ActionStatus.FAILED,"提交失败");
                    Intent intent = new Intent(ApplyVerifyActivity.this, ApplyTabHostActivity.class);
                    intent.putExtra("userloginflag", 1);
                    setResult(RESULT_OK, intent);
                    ApplyVerifyActivity.this.finish();
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_verify);
        //统计借款页面时间
        startTimes=TimeStatisticsUtil.getTime();
        // wifi管理器

        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        init();
        Intent intent = getIntent();
        capital = (Integer) intent.getSerializableExtra("capital");
        termLine = (Integer) intent.getSerializableExtra("termLine");
        contractNum = (String) intent.getSerializableExtra("contractNum");
        couponId = intent.getStringExtra("couponId");
        phoneJosn = (String) intent.getSerializableExtra("phoneJosn");
        initView();
    }

    private void initView() {
        button_apply_confirm = (Button) findViewById(R.id.button_apply_confirm);
         mWebView= (WebView) findViewById(R.id.mWebView);
         imageViewContract= (ImageView) findViewById(R.id.ImageView_contract);
        buttonContract= (Button) findViewById(R.id.button_contract);
        buttonApplyConfirm= (Button) findViewById(R.id.button_apply_confirm);
        WebSettings webSettings = mWebView.getSettings();
        //设置WebView性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(false);
        //设置可以访问文件
        webSettings.setAllowFileAccess(false);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(false);
        //加载需要显示的网页
        try {
            mWebView.loadUrl(Constants.API_ROOT + "/webview/applyConfirm?userId=" + Constants.LOGIN_USER.getId() + "&capital=" + capital + "&termLine=" + termLine.intValue());
        } catch (Exception e) {

        }

        //设置Web视图
        mWebView.setWebViewClient(new WebViewClient());

        ButtonListener listener = new ButtonListener();

        imageViewContract.setOnClickListener(listener);
        buttonContract.setOnClickListener(listener);
        buttonApplyConfirm.setOnClickListener(listener);
    }

    private class ButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(R.id.ImageView_contract==v.getId()) {
                if (isChecked) {
                    imageViewContract.setImageResource(R.drawable.set_off);
                    isChecked = false;

                } else {
                    imageViewContract.setImageResource(R.drawable.set_on);
                    isChecked = true;
                }
            }
            else if(R.id.button_contract==v.getId()) {
                Intent contractIntent = new Intent(ApplyVerifyActivity.this, DialogContractActivity.class);
                contractIntent.putExtra("url", "/webview/applyProtocol?userId=" + Constants.LOGIN_USER.getId() + "&capital=" + capital + "&termLine=" + termLine.intValue() + "&contractNum=" + contractNum);
                contractIntent.putExtra("title", "米米贷借款协议");
                startActivity(contractIntent);
            }
            else if(R.id.button_apply_confirm==v.getId()){
                    if (!isChecked) {
                        showShortToast1("请勾选米米贷协议");
                        return;
                    } else {
                        // 防止连续点击处理
                        if (fasterClickCheck()) {
                            return;
                        }
                        Map<String, String> systemInfo = SystemUtils.getSystemInfo(ApplyVerifyActivity.this);
                        if (systemInfo!=null) {
                            imei = systemInfo.get("imei");
                            if(TextUtils.isEmpty(imei)){
                                imeiJugeMsg();
                                return;
                            }
                        }
                        button_apply_confirm.setEnabled(false);
                        showWaitDialog();
                        //当前
                        @SuppressLint("WifiManagerLeak")
                        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                        //判断不同安卓系统版本对应获取到的mac地址
                        WifiInfoUtil infoUtil = new WifiInfoUtil(wifiManager);
                        if(!isUploadInstallApp) {
                            isUploadInstallApp=true;
                            getInstallApp();
                        }
                        //调用确认申请接口
                        getVertifyConfirmData();
                        saveUserConnectedWifi(infoUtil);
                    }
            }
        }

    }
    public void imeiJugeMsg(){
        final AlertDialog builder = new AlertDialog.Builder(this,R.style.Dialog).create();
        builder.show();
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_login_other_layout, null);
        builder.getWindow().setContentView(view);
        builder.setCanceledOnTouchOutside(false);
        Button button=(Button)view.findViewById(R.id.positiveButton);
        TextView msgTv=(TextView)view.findViewById(R.id.message);
        TextView titleTv = (TextView) view.findViewById(R.id.title);
        titleTv.setText("提示");
        msgTv.setText("您尚未开启手机设备串号读取权限，请开启相关权限！");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
    }

    /**
     * 保存手机连接wifi信息
     */
    public void saveUserConnectedWifi(final WifiInfoUtil infoUtil){

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                mapParams.put("mimidaiVersion", Constants.APP_VERSION);
                mapParams.put("mimidaiCode", Constants.APP_CODE + "");
                mapParams.put("data", new Gson().toJson(infoUtil.getWifiList()));
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/saveUserConnectedWifi",
                        mapParams, ApplyVerifyActivity.this);
            }
        }).start();

    }
    private void getInstallApp() {
        final List<AppInfo> appInfos = queryFilterAppInfo();
        Map<String, String> systemInfo = SystemUtils.getSystemInfo(ApplyVerifyActivity.this);
        if (systemInfo!=null) {
            imsi = systemInfo.get("imsi");
            imei = systemInfo.get("imei");
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                mapParams.put("data", new Gson().toJson(appInfos));
                mapParams.put("imei", imei==null?"":imei);
                if(!TextUtils.isEmpty(imsi)) {
                    mapParams.put("imsi", imsi == null ? "" : imsi);
                }
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/saveUserInstalledApp",
                        mapParams, ApplyVerifyActivity.this);
            }
        }).start();
    }

    private void getVertifyConfirmData() {

        if (isChecked) {
            if (Constants.BD_LOCATION == null) {
                showShortToast1("请开启定位权限，重新启动应用。");
                closeWaitDialog();
                return;
            }
            else{
                //如果此时关闭了系统获取位置权限，则需要通过当前位置是否为空判断
                if(TextUtils.isEmpty(Constants.BD_LOCATION.getAddrStr())){
                    showShortToast1("请开启定位权限，重新启动应用。");
                    closeWaitDialog();
                    return;
                }
            }
            applyLoanPost();

        } else {
            showShortToast1("请勾选米米贷借款协议");
            closeWaitDialog();
            button_apply_confirm.setEnabled(true);
        }
    }

    public void applyLoanPost(){
        String latitude=String.valueOf(Constants.BD_LOCATION.getLatitude());
        String lontitude=String.valueOf(Constants.BD_LOCATION.getLongitude());
        String province=String.valueOf(Constants.BD_LOCATION.getProvince());
        String city=String.valueOf(Constants.BD_LOCATION.getCity());
        String district=String.valueOf(Constants.BD_LOCATION.getDistrict());
        String detailAddress=Constants.BD_LOCATION.getAddrStr();
        //手机品牌
        String brand = android.os.Build.BRAND;
        //获取手机型号
        String model = android.os.Build.MODEL;
        //系统版本号
//                    String sdk = android.os.Build.VERSION.SDK;
        String release = android.os.Build.VERSION.RELEASE;
        Map<String, String> systemInfo = SystemUtils.getSystemInfo(ApplyVerifyActivity.this);
        if (systemInfo!=null){
            imsi = systemInfo.get("imsi");
            imei = systemInfo.get("imei");
        }
        //添加时间统计
        String applyEndTime = TimeStatisticsUtil.getTime();
        String applyStartTime = startTimes;
        final Map<String, String> param = new HashMap<String, String>();
        param.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
        param.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
        param.put("capital", capital.toString());
        param.put("termLine", termLine.intValue() + "");
        param.put("contractNum", contractNum);
        if (!TextUtils.isEmpty(couponId)) {
            param.put("couponId", couponId);
        }
        param.put("phoneBrand", brand);
        param.put("phoneModel", model);
        param.put("phoneOs", release);
        param.put("mimidaiVersion", Constants.APP_VERSION);
        param.put("imei", imei==null?"":imei);
        param.put("imsi", imsi==null?"":imsi);

        param.put("lng", lontitude);
        param.put("lat", latitude);
        param.put("province", province);
        param.put("city", city);
        param.put("area", district);
        param.put("detailAddress",detailAddress);
        param.put("startTime", applyStartTime);
        param.put("endTime", applyEndTime);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/loan/applyLoanNew", param, ApplyVerifyActivity.this);
                Message message = new Message();
                if (StringUtils.isBlank(result)) {
                    message.what = RESULT_ERROR;
                    handler.sendMessage(message);
                } else {
                    message.what = RESULT_OK;
                    message.obj = result;
                    handler.sendMessage(message);
                }

            }
        }).start();
    }

    public void intentNextPage(Third data){
        closeWaitDialog();
        if(data==null){
            CreditXAgent.onSubmit(ActionName.Submit.LOAN_SUBMISSION,
                    CreditXAgent.ActionStatus.FAILED,"提交失败");
            Intent intent = new Intent(ApplyVerifyActivity.this, ApplyTabHostActivity.class);
            intent.putExtra("userloginflag", 1);
            setResult(RESULT_OK, intent);
            ApplyVerifyActivity.this.finish();
        }
        else {
            showShortToast1(data.getMsg());
            button_apply_confirm.setEnabled(true);
            //保存成功，跳转到进度页面
            if (Constants.DEFAULT_SUCCESS_CODE.equals(data.getCode())) {
                CreditXAgent.onSubmit(ActionName.Submit.LOAN_SUBMISSION,
                        CreditXAgent.ActionStatus.SUCCESS,"提交成功");
                uploadContacts();
                Intent intent = new Intent(ApplyVerifyActivity.this, ApplyTabHostActivity.class);
                intent.putExtra("userloginflag", 1);
                setResult(RESULT_OK, intent);
                ApplyVerifyActivity.this.finish();
            }
            else{
                CreditXAgent.onSubmit(ActionName.Submit.LOAN_SUBMISSION,
                        CreditXAgent.ActionStatus.FAILED,"提交失败");
            }
            if (!isUploadInstallApp) {
                isUploadInstallApp = true;
                getInstallApp();
            }
        }
    }
    private static boolean isNullEmptyBlank(String str) {
        if (str == null || "".equals(str) || "".equals(str.trim()))
            return true;
        return false;
    }

    private List<AppInfo> queryFilterAppInfo() {
        pm = this.getApplicationContext().getPackageManager();

        // 查询所有已经安装的应用程序

        List<ApplicationInfo> listAppcations = pm
                .getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
        Collections.sort(listAppcations,
                new ApplicationInfo.DisplayNameComparator(pm));// 排序
        appInfos = new ArrayList<AppInfo>(); // 保存过滤查到的AppInfo
        // 根据条件来过滤


        for (ApplicationInfo app : listAppcations) {
            if ((app.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
                appInfos.add(getAppInfo(app));
            }
        }

        return appInfos;
    }

    private AppInfo getAppInfo(ApplicationInfo app) {
        Log.i("包名",app.packageName);
        AppInfo appInfo = new AppInfo();
        appInfo.setAppLabel((String) app.loadLabel(pm));
        appInfo.setPkgName(app.packageName);
        // loadIcon = app.loadIcon(pm);
        int id = app.uid;
        appInfo.setUid(id);
        //Bitmap bt_iamge = File2Code.drawableToBitmap(loadIcon);
//        voucherPic = File2Code.bitmapToBase64(bt_iamge, 500);

        // appInfo.setBase(voucherPic);
        return appInfo;
    }

    /**
     * 同步通讯录信息
     */
    private void uploadContacts() {
        if (isUpload) {
            return;
        }
        isUpload = true;
        if (!StringUtils.isBlank(phoneJosn)) {
            final Map<String, String> systemInfo = SystemUtils.getSystemInfo(ApplyVerifyActivity.this);
            if (systemInfo!=null){
                final String imei = systemInfo.get("imei");
                final String imsi = systemInfo.get("imsi");
            }

            if (Constants.LOGIN_USER!=null&&Constants.LOGIN_USER.getId()!=null){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Map<String, String> param = new HashMap<>();
                        param.put("userId", Constants.LOGIN_USER.getId() + "");
                        param.put("imei", imei==null?"":imei);
                        param.put("imsi",imsi==null?"":imsi);
                        param.put("phoneContacts", phoneJosn);
                        String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/uploadUserPhoneContacts", param);
                    }
                }).start();
            }

        }
    }

    /**
     * 开启定位服务
     */
    private void location() {
        Constants.LOCATION_LISTENER = new MyLocationListener();
        Constants.LOCATION_CLIENT = new LocationClient(this);
        Constants.LOCATION_CLIENT.registerLocationListener(Constants.LOCATION_LISTENER);
        Constants.LOCATION_CLIENT.setLocOption(initLocation());
        if (!Constants.LOCATION_CLIENT.isStarted()) {
            Constants.LOCATION_CLIENT.start();
        }
    }

    private LocationClientOption initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 0;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(false);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(true);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        return option;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null && dialog.isShowing()) {
            dialog.cancel();
        }

    }
}
